@Service
public class ExportService {

    @Autowired
    private TemperatureRepository temperatureRepository;

    @Value("${export.batch-size:1000}")
    private int batchSize;

    public void exportTemperatureRecords(ExportCriteria criteria, 
                                       ExportType exportType,
                                       OutputStream outputStream) {
        
        // 构建查询条件
        Specification<TemperatureRecord> spec = Specification.where(
                TemperatureSpecifications.betweenDates(
                        criteria.getStartDate().atStartOfDay(),
                        criteria.getEndDate().atTime(23, 59, 59))
        ).and(TemperatureSpecifications.temperatureBetween(
                criteria.getMinTemp(), 
                criteria.getMaxTemp()));

        // 选择导出列
        List<String> selectedColumns = Optional.ofNullable(criteria.getColumns())
                .filter(c -> !c.isEmpty())
                .orElseGet(() -> Arrays.asList("username", "temperature", "reportTime"));

        // 使用游标分页处理
        try (ScrollableResults<TemperatureRecord> scroll = temperatureRepository.streamBy(spec)) {
            
            ExportStrategy strategy = ExportStrategyFactory.getStrategy(exportType);
            strategy.init(outputStream, selectedColumns);

            int count = 0;
            while (scroll.hasNext()) {
                TemperatureRecord record = scroll.next();
                strategy.writeRow(convertToRowData(record, selectedColumns));
                
                if (++count % batchSize == 0) {
                    strategy.flush();
                }
            }
            strategy.finish();
        }
    }

    private Map<String, Object> convertToRowData(TemperatureRecord record, List<String> columns) {
        Map<String, Object> row = new LinkedHashMap<>();
        for (String col : columns) {
            switch (col) {
                case "username":
                    row.put(col, record.getUser().getUsername());
                    break;
                case "temperature":
                    row.put(col, record.getTemperature());
                    break;
                case "reportTime":
                    row.put(col, record.getReportTime().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
                    break;
                // 其他字段处理...
            }
        }
        return row;
    }
}